//
//  LPFComposePictureView.swift
//  WeiBo
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

// cell可重用标示符
private let LPFComposePictureViewCellId = "LPFComposePictureViewCellId"

class LPFComposePictureView: UICollectionView {
    
    // MARK: - 保存外界传进来的图片
    var images: [UIImage] = [UIImage]()
    
    // MARK: - 闭包 告知外界弹出选择图片控制器
    var ComposePictureViewClosure: (() -> ())?
    
    // MARK: - 供外界调用方法
    // 提供image
    func addImage(image: UIImage){
        //添加到数组
        images.insert(image, atIndex: 0)
        
        // 当用户添加的图片超出9张我们就把最先添加的图片删除掉
        if images.count > 9{
            images.removeLast()
    }
        
        // 如果数组大于0 显示view
        if images.count > 0{
            self.hidden = false
        }
        
        self.reloadData()
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    // MARK: - 设置视图
    private func setupUI(){
        self.backgroundColor = UIColor.whiteColor()
        
        // 隐藏配图view
        self.hidden = true
        
        self.dataSource = self
        
        self.delegate = self
        // 注册cell
        registerClass(LPFComposePictureViewCell.self, forCellWithReuseIdentifier: LPFComposePictureViewCellId)
        
        let margin: CGFloat = 5
        
        let cellWH = (SCREENW - 20 - margin * 2) / 3
        
        //获取layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        // 设置垂直间距和水平间距
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
    }
    
    
    
}

// MARK: - 数据源 代理
extension LPFComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //判断图片个数  显示加号图片
        let count = images.count
        if count == 0 || count == 9{
            return count
        }else{
            return count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LPFComposePictureViewCellId, forIndexPath: indexPath) as! LPFComposePictureViewCell
        
        if indexPath.item == images.count{
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        
        cell.composePictureViewCellClosure = {[weak self] in
            
            //删除图片
            self?.images.removeAtIndex(indexPath.item)
            
            if self?.images.count <= 0{
                self?.hidden = true
            }
            self?.reloadData()
        }
        
        return cell
    }
    
    //点击方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if indexPath.item == images.count{
            ComposePictureViewClosure?()
        }
    }
}

// MARK: - 自定义cell
class LPFComposePictureViewCell: UICollectionViewCell{
    
    // MARK: - 闭包
    var composePictureViewCellClosure: (() -> ())?
    
    // MARK: - 外界调用 设置图片
    var image: UIImage?{
        didSet{
            if image != nil{
                bgImageView.image = image
                // 解决cell复用问题
                bgImageView.highlightedImage = nil
                // 显示删除按钮
                deleteButton.hidden = false
            }else{
                bgImageView.image = UIImage(named: "compose_pic_add")
                // 解决cell复用问题
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                // 隐藏删除按钮
                deleteButton.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
        
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    
    private lazy var deleteButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    // MARK: - 删除按钮点击事件
    @objc private func deleteButtonClick(){
        composePictureViewCellClosure?()
    }
}
